package com.bete.updata;

import static com.bete.updata.UpdateConstant.DOWNLOAD_PATH;
import static com.bete.updata.UpdateConstant.PACKAGENAME;
import static com.bete.updata.UpdateConstant.UPDATEFILEPATH;
import static com.bete.updata.UpdateConstant.UPLOAD_PATH;
import static com.bete.updata.UpdateConstant.UPLOAD_URL;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.BaseAdapter;

import java.io.IOException;
import java.util.LinkedList;

import me.jessyan.autosize.utils.LogUtils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class UpLoadDataActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        overridePendingTransition(0, 0);
        setContentView(R.layout.activity_updata);
        // 需要传递的数据
        //1. 文件名称
        // 2. 文件大小 （可选）
        //3. 文件路径
        // 4. 上传路径
        String url = getIntent().getStringExtra(UPLOAD_URL);
        String uploadPath = getIntent().getStringExtra(UPLOAD_PATH);
        String updateFilePath = getIntent().getStringExtra(UPDATEFILEPATH);
        String packageName = getIntent().getStringExtra(PACKAGENAME);
        LinkedList<String> fileNames = new LinkedList<>();
        fileNames.add(updateFilePath);

        OkhttpUploadUtil.getInstance().doPostRequest(url, uploadPath,fileNames, new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                Intent intent = new Intent();
                intent.putExtra(UpdateConstant.SENDMESSAGE, getString(R.string.shangchuanshibai));
                intent.setAction("com.bete.upload.recever");
                sendBroadcast(intent);
                restartApp(packageName);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Intent intent = new Intent();
                intent.putExtra(UpdateConstant.SENDMESSAGE, getString(R.string.shangchuanchenggong));
                intent.setAction("com.bete.upload.recever");
                sendBroadcast(intent);
                restartApp(packageName);

            }
        });

    }


    // 重新启动应用
    private void restartApp(String packageName) {
        //1. 移除Launcher
        LogUtils.d(" packageName is :" + packageName);
        Intent launchIntent = getPackageManager().getLaunchIntentForPackage(packageName);
        if (launchIntent != null) {
            // 清除栈并启动应用的启动 Activity
            launchIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            launchIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            startActivity(launchIntent);
            overridePendingTransition(0, 0);
        }

    }
}
